package com.xxin.controller.sys;

import com.xxin.pojo.dto.LoginDTO;
import com.xxin.pojo.vo.CurrentUserVO;
import com.xxin.service.SysUsersService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author 小欣
 * @version 1.0
 * @since 1.8
 */
@Controller
public class LoginController {
	
	private final Logger log = LogManager.getLogger(LoginController.class);
	
	@Resource
	private SysUsersService sysUsersService;
	
	@Value("${cookie.timeout}")
	private Integer cookieTimeout;
	
	@Value("${current.user.sessionKey}")
	private String currentUserSessionKey;
	
	/*
	用户登录
	 */
	@PostMapping("/doLogin")
	public String doLogin(LoginDTO loginDTO, HttpSession session, HttpServletResponse httpServletResponse, Model model){
		log.info("前端请求的数据为:{}",loginDTO.toString());
		
		CurrentUserVO currentUserVO = null;
		try {
			currentUserVO = sysUsersService.doLogin(loginDTO);
		} catch (Exception e) {
			model.addAttribute("error",e.getMessage());
			return "login";
		}
		session.setAttribute(currentUserSessionKey,currentUserVO);
		session.setMaxInactiveInterval(cookieTimeout);
		Cookie jsessionid = new Cookie("JSESSIONID", session.getId());
		jsessionid.setMaxAge(cookieTimeout);
		httpServletResponse.addCookie(jsessionid);
		return "redirect:main";
	}
}
